<template>
  <div class="content">
    <div v-for="item in carouselList" :key="item.configId" class="imgs">
      <el-image class="img" :src="item.url"></el-image>
      <el-button
        class="buttons"
        size="mini"
        plain
        type="danger"
        @click="deleteCarousel(item.configId)"
        >删除</el-button
      >
    </div>
    <el-upload
      class="imgUpload"
      ref="upload_attach"
      action="abc"
      list-type="picture-card"
      accept="image/*"
      :limit="1"
      :file-list="imgFileList"
      :auto-upload="false"
      :on-change="handleFileChange"
      :http-request="submitUploadImg"
      :show-file-list="false"
    >
      <i class="el-icon-plus"></i>
      <div class="el-upload__tip" slot="tip">
        图片大小不超过2Mb，推荐长宽比5:3
      </div>
    </el-upload>
    <cropper
      v-if="showCropper"
      :dialog-visible="showCropper"
      :cropper-img="cropperImg"
      @update-cropper="updateCropper"
      @colse-dialog="closeDialog"
      @upload-img="uploadImg"
    />
  </div>
</template>
<script>
import Cropper from "../utils/cropper.vue";
import CompressImg from "../utils/compressImg.js";
import Config from "../config";
import loading from "../../loading";
export default {
  components: {
    Cropper,
  },
  data() {
    return {
      carouselList: [],
      imgFileList: [],
      cropperImg: "", // 需要裁剪的图片
      showCropper: false, // 是否显示裁剪框
      blobImg: "",
    };
  },
  created() {
    this.getCarousel();
  },
  mounted() {},
  methods: {
    async getCarousel() {
      if (window.sessionStorage.getItem("carousel") != null) {
        this.carouselList = JSON.parse(
          window.sessionStorage.getItem("carousel")
        );
        console.log("已从本地获得轮播图l！", this.carouselList);
        return;
      }
      const res = await this.$axios.get(`${this.HOST}/config/api/carousel`);
      console.log("获取轮播图成功！", res.data.data);
      this.carouselList = [];
      res.data.data.carousel.forEach((element) => {
        element.url = Config.picPrefixUrl + element.url;
        this.carouselList.push(element);
      });
      window.sessionStorage.setItem(
        "carousel",
        JSON.stringify(this.carouselList)
      );
    },
    /**
     * 上传轮播图
     */
    async submitUploadImg() {
      let formData = new FormData();
      formData.append("file", this.blobImg);
      const _loading = loading("上传中，请稍等...");
      const config = {
        onUploadProgress: (progressEvent) => {
          this.progressPercent = Number(
            ((progressEvent.loaded / progressEvent.total) * 100).toFixed(0)
          );
          _loading.setText("上传中，进度：" + this.progressPercent + "%"); //更新dialog进度，优化体验
        },
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };
      try {
        const res = await this.$axios.post(
          `${this.HOST}/config/api/uploadCarousel`,
          formData,
          config
        );
        if (res.data.meta.code == 200) {
          this.$message({
            message: "添加成功！",
            type: "success",
            showClose: true,
          });
          window.sessionStorage.removeItem("carousel");
          this.getCarousel();
        }
      } finally {
        this.imgFileList.pop();
        _loading.close();
      }
    },
    handleFileChange(file) {
      const { raw } = file;
      this.openCropper(raw);
    },
    openCropper(file) {
      var files = file;
      let isLt2M = files.size > 2 << 20;
      if (isLt2M) {
        this.$message.error("请上传2M内的图片");
        return false;
      }
      var reader = new FileReader();
      reader.onload = (e) => {
        let data;
        if (typeof e.target.result === "object") {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        this.cropperImg = data;
      };
      // 转化为base64
      // reader.readAsDataURL(file)
      // 转化为blob
      reader.readAsArrayBuffer(files);
      this.showCropper = true;
    },
    // 上传图片
    async uploadImg(file) {
      // console.log("bef file", file);
      let img = await CompressImg(file);
      console.log("img", img);
      this.blobImg = img.file;
      this.showCropper = false;
      this.submitUploadImg();
    },
    updateCropper() {
      this.$refs.fileUpload.$children[0].$el.click();
    },
    // 关闭窗口
    closeDialog() {
      this.imgFileList.pop();
      this.showCropper = false;
    },
    /**
     * 删除轮播图
     */
    deleteCarousel(id) {
      this.$confirm("此操作将永久删除该轮播图, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        const res = await this.$axios.get(
          `${this.HOST}/config/api/deleteCarousel/${id}`,
          {}
        );
        if (res.data.meta.code == 200) {
          this.$message({
            message: "删除成功",
            type: "success",
            showClose: true,
          });
          this.carouselList = [];
          window.sessionStorage.removeItem("carousel");
          this.getCarousel();
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.content {
  padding-left: 30px;
  padding-right: 30px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  .imgs {
    margin-bottom: 10px;
    width: 420px;
    text-align: right;

    .img {
      box-shadow: 0px 0px 10px gray;
      border-radius: 2px;
      width: 420px;
      height: 252px; // 5:3
    }

    .buttons {
      margin-right: 10px;
      margin-bottom: 5px;
    }
  }

  .imgUpload {
    width: 420px;
    padding-left: 20px;
  }
}
</style>